//
//  HttpConfig+Session.swift
//  Health-Doctor
//
//  Created by 勇胡 on 2022/11/25.
//  Copyright © 2022 掌上卫健. All rights reserved.
//用来配置https时证书验证

import Foundation
import Moya
import Alamofire

extension TargetType{
    
    
    static func custoSession() -> Session {
        let defaultSession = MoyaProvider<Self>.defaultAlamofireSession()
//        //线上环境
//        if UrlConfigItem.isOnline(){
//            
//            //线上环境，通过IP（非域名），设置受信任，不设置会报错 该服务器证书不受信任
//            if UrlConfigItem.isOnlineAndIp(){
//                let domainSets = LibsManager.getSessionDomains()
//                var policies: [String: ServerTrustEvaluating] = [:]
//                for domain in domainSets {
//                    //不校验证书
//                    policies[domain] = DisabledTrustEvaluator()
//                }
//                let manager = ServerTrustManager(allHostsMustBeEvaluated: false, evaluators: policies)
//                return Session(configuration: defaultSession.sessionConfiguration, serverTrustManager: manager)
//            }
            //域名方式默认证书验证
            return defaultSession
//        }
        
//        //下面是开发环境
//        //获取APP所涉及的域名，测试环境才使用我们自定义的woniu.cn.cer证书，才设置这些白名单，线上不使用该证书
//        //加载指定证书
//        let configuration = defaultSession.sessionConfiguration
//        let pathToCert = Bundle.main.path(forResource: "woniu.cn", ofType: "cer")
//        if let path:String = pathToCert {
//            ///添加证书
//            do {
//                let certificationData = try Data(contentsOf: URL(fileURLWithPath: path)) as CFData
//                if let certificate = SecCertificateCreateWithData(nil, certificationData){
//                    //https://www.jianshu.com/p/19a0c5a81624
//                    let certificates: [SecCertificate] = [certificate]
//                    let item = PinnedCertificatesTrustEvaluator(certificates: certificates, acceptSelfSignedCertificates: true, performDefaultValidation: true, validateHost: false)
//                    
//                    ///配置证书域名
//                    let domainSets = LibsManager.getSessionDomains()
//                    var policies: [String: ServerTrustEvaluating] = [:]
//                    for domain in domainSets {
//                        //只有内网不校验证书，其他环境校验证书 (开发、测试、线上都校验)
//                        if domain.contains("192.") || domain.contains("120."){
//                            policies[domain] = DisabledTrustEvaluator()
//                        }else{
//                            policies[domain] = item
//                        }
//                    }
//                    let manager = ServerTrustManager(allHostsMustBeEvaluated: false, evaluators: policies)
//                    return Session(configuration: configuration, serverTrustManager: manager)
//                }
//            } catch {
//                return Session(configuration: configuration)
//            }
//        }
//        return Session(configuration: configuration)
    }
}

extension URLRequest{
    
    /// 写入到日志文件
    public func writeToLogFile(){
        var logStr = "cloudAPI请求地址(\(self.httpMethod ?? "")): \(self.url?.absoluteString ?? "")"
        if let body = self.httpBody, let bodyString = String(data: body, encoding: .utf8) {
            logStr.append("，请求参数: \(bodyString)")
        }
#if DEBUG
        print("\n==>\(logStr)\n")
#endif
//        let date = DateUtil.currentDateTime(format: "yyyy-MM-dd HH:mm:ss")
//        LogHelper.shared.writeToFile("\n-->\(date)\(logStr)\n")
    }
}

///日志拦截器，接口请求拦截器
class NetworkLoggerPlugin: PluginType {
    // 创建日志插件实例
    static let share = NetworkLoggerPlugin()
    //是否已经打印了完整的登录信息
    private var isDidLogAppInfo = false
    private let notLogAPISet:Set<String> = ["phisb/medicines/list",
                                            "cloudauth/doctor/getDoctorList","cloudauth/doctor/getLocalDoctorList",
                                            "phs/spkg/cache",
                                            "phisb/notice/notifys","phisb/template/listSpkgTemplateAll"]
    
    public class func plugins()->[NetworkLoggerPlugin]{
        return [share]
    }
    
    
    // 在请求发送之前调用
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        
#if DEBUG
        var logStr = "请求地址(\(request.httpMethod ?? "")): \(request.url?.absoluteString ?? "")"
        if let body = request.httpBody, let bodyString = String(data: body, encoding: .utf8) {
            logStr.append("请求参数: \(bodyString)")
        }
        print("\n==>\(logStr)\n")
#endif
        //因为APP启动的时候，还没有登录信息，当有登录信息后需要重新打印一次当前登录信息
//        if isDidLogAppInfo == false && !UrlConfig.shared.authToken.isEmpty{
//            isDidLogAppInfo = true
//            //写APP信息日志文件
//            LogHelper.shared.writeAppInfoToFile()
//        }
        return request
    }
    
    // 在请求发送之后、收到响应之前调用
    func willSend(_ request: RequestType, target: TargetType) {
        //发现这里用属性方式记录请求开始时间，在部分手机上偶发崩溃，定位就是这个方法里面多线程导致的，不知道第三方框架里面的实现。
    }
    
    // 在收到响应之后调用
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        
        var resultStr = ""
        switch result {
        case .success(let response):
            if notLogAPISet.contains(target.path){
                resultStr = "返回结果\(response.statusCode)(\(target.path)): 数据量大，不打印\r\n"
            }else{
                if let responseString = String(data: response.data, encoding: .utf8) {
                    resultStr = "返回结果\(response.statusCode)(\(target.path)): \(responseString)\r\n"
                }
            }
#if DEBUG
            print("\n<==\(resultStr)")
#endif
            
        case .failure(let error):
            resultStr = "\(target.path)请求失败: \(error.localizedDescription)\r\n"
            YBLog(resultStr)
        }
//        let date = DateUtil.currentDateTime(format: "yyyy-MM-dd HH:mm:ss")
//        LogHelper.shared.writeToFile("\n<===\(date)\(resultStr)")
    }
    
}

